const { muser } = require('../../models/system/muser');
const EmailService = require('../../services/system/emailService');
const response = require('../../utils/response');
const { role } = require('../../models/system/mrole');
const { sign } = require('../../utils/auth');
const { easyCopy } = require('../../utils/utils');


class EmailController {
    // 发送验证码邮件
    static async sendVerificationCode(ctx) {
        const { email } = ctx.request.body;
        try {
            await EmailService.sendVerificationCode(email);
            response.success(ctx, { message: '验证码发送成功' });
        } catch (err) {
            response.error(ctx, { message: err?.message || '验证码发送失败' });
        }
    }

    // 验证邮箱验证码
    static async verifyCode(ctx) {
        const { email, code } = ctx.request.body;
        try {
            const isValid = await EmailService.verifyCode(email, code);

            if (isValid) {
                const getRolesByIds = async (roleIds) => {
                    const roles = await role.find({ _id: { $in: roleIds } }).populate('roles').lean();
                    return roles.map(e => e.name);
                }
                await muser.findOne({ email }).then(async user => {
                    if (user) {
                        const token = sign({ id: user._id });
                        const roles = await getRolesByIds(user.roles);
                        const userData = easyCopy(user);
                        userData.roles = roles;
                        delete userData.password;
                        response.success(ctx, { message: '验证成功', data: { token, user: userData } });
                    } else {
                        await muser.create({
                            email,
                            username: email.split('@')[0],
                        }).then(async user => {
                            const token = sign({ id: user._id });
                            const roles = await getRolesByIds(user.roles);
                            const userData = easyCopy(user);
                            userData.roles = roles;
                            delete userData.password;
                            response.success(ctx, { message: '验证成功', data: { token, user: userData } });
                        })
                        // response.error(ctx, { message: '用户不存在' });
                    }
                })
            }

            // isValid ? response.success(ctx, { message: '验证成功' })
            //     : response.error(ctx, { message: '验证码错误' });

        } catch (err) {
            response.error(ctx, { message: err?.message || '验证失败' });
        }
    }
}

module.exports = EmailController;
